package com.labichaoka.chaoka.utils;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.text.TextUtils;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.labichaoka.chaoka.base.MyApplication;
import com.labichaoka.chaoka.entity.ContactBean;
import com.tencent.mm.opensdk.utils.Log;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by ruan on 2018/7/19.
 */

public class UploadUtil {

    private Context mContext;
    /**
     * 获取库Phone表字段
     **/
    private static final String[] PHONES_PROJECTION = new String[]{ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Photo.PHOTO_ID,
            ContactsContract.CommonDataKinds.Phone.CONTACT_ID};
    /**
     * 电话号码
     **/
    private static final int PHONES_NUMBER_INDEX = 1;
    /**
     * 联系人显示名称
     **/
    private static final int PHONES_DISPLAY_NAME_INDEX = 0;

    private UploadCallBack uploadCallBack;


    public UploadUtil() {
        mContext=MyApplication.mContext;
    }

    private AMapLocationClient mLocationClient;
    private AMapLocationClientOption mLocationOption;


    /**
     * 获取通讯录
     *
     * @return
     */
    public List<ContactBean> getPhoneContacts() {
        List<ContactBean> mContactsBeanList = new ArrayList<>();
        ContentResolver resolver = mContext.getContentResolver();
        try {
            // 获取手机联系人
            Cursor cursor = resolver.query(Phone.CONTENT_URI, PHONES_PROJECTION, null, null, null);
            if (cursor != null) {
                while (cursor.moveToNext()) {
                    // 得到手机号码
                    String phoneNumber = cursor.getString(PHONES_NUMBER_INDEX);
                    // 当手机号码为空的或者为空字段 跳过当前循环
                    if (TextUtils.isEmpty(phoneNumber)) {
                        continue;
                    }
                    // 得到联系人名称
                    String contactName = cursor.getString(PHONES_DISPLAY_NAME_INDEX);
                    ContactBean mContactsBean = new ContactBean();
                    mContactsBean.setContactsName(contactName);
                    mContactsBean.setPhoneNumber(phoneNumber);
                    mContactsBeanList.add(mContactsBean);
                }
                cursor.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return mContactsBeanList;
    }

    /*
    * 获取定位
    */
    public void getLocation() {
        //初始化定位
        //声明AMapLocationClient类对象
        mLocationClient = new AMapLocationClient(mContext);
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否允许模拟位置,默认为true，允许模拟位置
        mLocationOption.setMockEnable(true);
        //单位是毫秒，默认30000毫秒，建议超时时间不要低于8000毫秒。
        mLocationOption.setHttpTimeOut(20000);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //关闭缓存机制
        mLocationOption.setLocationCacheEnable(false);

        mLocationClient.setLocationOption(mLocationOption);
        //设置场景模式后最好调用一次stop，再调用start以保证场景模式生效
        mLocationClient.stopLocation();
        mLocationClient.startLocation();


    }

    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    //可在其中解析amapLocation获取相应内容。
                    amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                    amapLocation.getLatitude();//获取纬度
                    amapLocation.getLongitude();//获取经度
                    amapLocation.getAccuracy();//获取精度信息
                    amapLocation.getAddress();//地址，如果option中设置isNeedAddress为false，则没有此结果，网络定位结果中会有地址信息，GPS定位不返回地址信息。
                    amapLocation.getCountry();//国家信息
                    amapLocation.getProvince();//省信息
                    amapLocation.getCity();//城市信息
                    amapLocation.getDistrict();//城区信息
                    amapLocation.getStreet();//街道信息
                    amapLocation.getStreetNum();//街道门牌号信息
                    amapLocation.getCityCode();//城市编码
                    amapLocation.getAdCode();//地区编码
                    amapLocation.getAoiName();//获取当前定位点的AOI信息
                    amapLocation.getBuildingId();//获取当前室内定位的建筑物Id
                    amapLocation.getFloor();//获取当前室内定位的楼层
                    amapLocation.getGpsAccuracyStatus();//获取GPS的当前状态
                    //获取定位时间
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date date = new Date(amapLocation.getTime());
                    df.format(date);

                    System.out.print(amapLocation);

                    //定位信息获取完成后再调用检查更新
                    uploadCallBack.uploadSuccessCallBack(amapLocation.getAddress());

                    mLocationClient.stopLocation();
                    mLocationClient.onDestroy();

                } else {
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError", "location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                    uploadCallBack.uploadFailCallBack(amapLocation.getErrorCode()+"  "+amapLocation.getErrorInfo());
                }
            }


        }
    };

    public void setCallBack(UploadCallBack uploadCallBack) {
        this.uploadCallBack = uploadCallBack;
    }

    public interface UploadCallBack {
        void uploadSuccessCallBack(String str);

        void uploadFailCallBack(String str);
    }


}
